package com.softserveinc.moviedbapp.connection;

import android.net.http.AndroidHttpClient;
import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class InputStreamProvider {

	private static String TAG = InputStreamProvider.class.getSimpleName();

	private final URL movieApiUrl;
	final AndroidHttpClient mClient;
	final HttpGet mGETRequest;

	/* constructor */
	public InputStreamProvider(final String url) {
		try {
			movieApiUrl = new URL(url);
			mClient = AndroidHttpClient.newInstance("Android");
			mGETRequest = new HttpGet(url);
		} catch (MalformedURLException e) {
			throw new RuntimeException(e);
		}
	}

	public InputStream getInputStream() {
		Log.d(TAG, "inside getInputStream()");
		InputStream inputStream = null;

		try {
			HttpResponse response = mClient.execute(mGETRequest);
			final int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				Log.w("ImageDownloader", "Error " + statusCode + " while opening input stream for " + movieApiUrl);
				return null;
			}
			final HttpEntity entity = response.getEntity();
			if (entity != null) {
				inputStream = entity.getContent();
			}
		} catch (IllegalStateException e) {
			Log.e(TAG, "failed to open an input stream. ", e);
		} catch (IOException e) {
			Log.e(TAG, "failed to open an input stream. ", e);
		}

		return inputStream;
	}

	public void closeHttpClient() {
		if (mClient != null) {
			mClient.close();
		}
	}
}
